package org.simplecrm.repository.event;

import org.simplecrm.domain.event.Event;
import org.slf4j.Logger;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Implementation for JDBC database.
 */
@Repository("eventDAO")
public class EventJdbcDAO implements EventDAO {

    @org.simplecrm.misc.loginject.Logger
    private Logger LOGGER;

    @PersistenceContext(unitName = "entityManager")
    private EntityManager entityManager;

    @Override
    public List<Event> getEventsPage(int customerId, int pageNumber, int pageSize) {

        List<Event> eventsPage;

        //TODO: is it a good solution to obtain data on every page request???
        Query query = entityManager.createQuery("From Event e Where e.customer.id = :customerId");
        query.setParameter("customerId", customerId);
        query.setFirstResult((pageNumber - 1) * pageSize);
        query.setMaxResults(pageSize);
        eventsPage = query.getResultList();

        return eventsPage;
    }

    @Override
    public Long getEventsCount(int customerId) {
        Query query = entityManager.createNamedQuery("Event.count");
        query.setParameter("customerId", customerId);
        return (Long) query.getSingleResult();
    }

    @Override
    public Event getEventById(int id) {
        return entityManager.find(Event.class, id);
    }

    @Override
    public void deleteEvent(int id) {

        Event event = entityManager.find(Event.class, id);
        entityManager.remove(event);
    }

    @Override
    public void addNewEvent(Event newEvent) {
        entityManager.persist(newEvent);
    }

    @Override
    public void updateEvent(Event updatedEvent) {
        entityManager.find(Event.class, updatedEvent.getId());
        entityManager.merge(updatedEvent);
    }
}
